package com.uf.util;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSource;

public class ConnectionHelper {
	
	private static Properties getConfig(){
		try {
			Properties prop = new Properties();
			Class cla = ConnectionHelper.class;
			cla = Class.forName("com.uf.util.ConnectionHelper");
			InputStream is = cla.getResourceAsStream("/db.properties");
			prop.load(is);
			
			return prop;
			
			
		} catch (Exception e) {
			throw new RuntimeException("加载数据库配置文件失败!", e);
		}		
	}
	
	private static DataSource ds = null;
	private static synchronized DataSource getDSLocal(){
		if(ds == null){
			Properties prop = getConfig();
			
			BasicDataSource bds = new BasicDataSource();
			
			bds.setDriverClassName(prop.getProperty("dbdriver"));
			bds.setUrl(prop.getProperty("dburl"));
			bds.setUsername(prop.getProperty("dbuser"));
			bds.setPassword(prop.getProperty("dbpwd"));
			String num = prop.getProperty("dbmaxactive");
			if(num != null && !num.equals(""))
				bds.setMaxActive(Integer.parseInt(num));
			ds = bds;
		}
		return ds;
	}
	
	public static Connection getConnection(){
		try {
			return getDSLocal().getConnection();
		} catch (SQLException e) {
			throw new RuntimeException("获取链接失败!", e);
		}
	}
	public static void closeConnection(Connection conn){
		try {
			if(conn != null)
				conn.close();
		} catch (SQLException e) {
			throw new RuntimeException("获取链接失败!", e);
		}
	}
	
	
	
}
